<template>
	<view>
		<!-- 扫码-->
		<view @click="handleScanQR" class="header-icon">
			<view class="menu-item-box">
				<view class="iconfont icon-scan"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import uQRCode from "@/uni_modules/Sansnn-uQRCode/components/u-qrcode/u-qrcode.vue"
	export default {
		name: "scan-QR-codes",
		data() {
			return {

			};
		},
		methods: {
			// 扫码
			async handleScanQR() {
				try {
					// 执行扫码
					const res = await uni.scanCode({
						onlyFromCamera: true,
						scanType: ['qrCode', 'barCode']
					});

					// 处理可能的数组格式结果
					let scanResult = null;
					if (Array.isArray(res)) {
						// 查找数组中第一个非空的有效结果
						const validResult = res.find(item => item && item.result);
						scanResult = validResult ? validResult.result : null;
					} else if (res && res.result) {
						// 标准对象格式
						scanResult = res.result;
					}

					// console.log('完整扫码响应:', JSON.stringify(res, null, 2));
					// console.log('解析后的扫码结果:', scanResult);

					if (scanResult) {
						this.$modal.msgSuccess('扫码成功');

						// 处理扫码结果（例如打开链接）
						this.processScanResult(scanResult);
					} else {
						throw new Error('未获取到有效扫码结果');
					}
				} catch (err) {
					console.error('扫码失败:', err);
					this.$modal.msgError(err.message)
				}
			},

			// 处理扫码结果
			processScanResult(result) {
				console.log("处理扫码结果：" + result);
				// 判断结果类型并处理
				if (result.startsWith('http')) {
					// 如果是网址则打开
					this.$tab.navigateTo('/pages/common/webview/index?url=' + result);
				} else if (result.startsWith('{') || result.startsWith('[')) {
					// 尝试解析JSON数据
					try {
						const data = JSON.parse(result);
						return data;
						console.log('JSON格式扫码内容:', data);
						// 处理自定义数据结构...
					} catch (e) {
						console.warn('非标准JSON格式:', result);
						this.showResultDialog(result);
					}
				} else {
					// 显示纯文本结果
					this.showResultDialog(result);
				}
			},

			// 显示结果对话框
			showResultDialog(content) {
				uni.showModal({
					title: '扫码结果',
					content: content,
					confirmText: '确定',
					showCancel: false
				});
			},

			// 检查相机权限（全平台兼容）
			async checkCameraPermission() {
				// #ifdef MP-WEIXIN
				// 微信小程序平台
				try {
					const setting = await uni.getSetting();
					if (!setting.authSetting || !setting.authSetting['scope.camera']) {
						await uni.authorize({
							scope: 'scope.camera'
						});
					}
				} catch (authErr) {
					if (authErr.errMsg.includes('auth deny')) {
						await this.showAuthModal('需要相机权限', '请允许使用相机进行扫码');
					}
				}
				// #endif

				// #ifdef APP-PLUS
				// App平台（iOS/Android）
				const platform = uni.getSystemInfoSync().platform;
				if (platform === 'android') {
					const status = await this.checkAndroidPermission();
					if (status !== 'granted') {
						await this.requestAndroidPermission();
					}
				} else if (platform === 'ios') {
					const status = await this.checkIOSPermission();
					if (status !== 'authorized') {
						await this.requestIOSPermission();
					}
				}
				// #endif

				// #ifdef H5
				// H5平台权限处理
				if (typeof navigator === 'undefined' || !navigator.mediaDevices || !navigator.mediaDevices
					.getUserMedia) {
					throw new Error('当前浏览器不支持相机访问');
				}
				try {
					// 尝试访问摄像头
					const stream = await navigator.mediaDevices.getUserMedia({
						video: true
					});
					// 立即关闭流，因为我们只是检查权限
					stream.getTracks().forEach(track => track.stop());
				} catch (h5Err) {
					throw new Error('相机访问被拒绝：' + h5Err.message);
				}
				// #endif
			},

			// Android权限检查
			checkAndroidPermission() {
				return new Promise((resolve) => {
					plus.android.requestPermissions(
						['android.permission.CAMERA'],
						(resultObj) => {
							if (resultObj.deniedAlways && resultObj.deniedAlways.length > 0) {
								resolve('deniedAlways'); // 永久拒绝
							} else if (resultObj.denied && resultObj.denied.length > 0) {
								resolve('denied'); // 暂时拒绝
							} else {
								resolve('granted'); // 已授权
							}
						},
						(error) => {
							resolve('error');
						}
					);
				});
			},

			// Android权限请求
			requestAndroidPermission() {
				return new Promise((resolve, reject) => {
					plus.android.requestPermissions(
						['android.permission.CAMERA'],
						(resultObj) => {
							if (resultObj.denied && resultObj.denied.length === 0) {
								resolve();
							} else {
								reject('权限被拒绝');
							}
						},
						(error) => {
							reject(error);
						}
					);
				});
			},

			// iOS权限检查
			checkIOSPermission() {
				return new Promise((resolve) => {
					const AVCaptureDevice = plus.ios.importClass('AVCaptureDevice');
					const authStatus = AVCaptureDevice.authorizationStatusForMediaType(
						'vide'); // 注意：'vide'代表视频媒体类型
					// iOS授权状态: 0=未决定, 1=限制, 2=拒绝, 3=授权
					switch (authStatus) {
						case 3:
							resolve('authorized');
							break;
						case 2:
							resolve('denied');
							break;
						case 1:
							resolve('restricted');
							break;
						default:
							resolve('notDetermined');
					}
				});
			},

			// iOS权限请求
			requestIOSPermission() {
				return new Promise((resolve, reject) => {
					const AVCaptureDevice = plus.ios.importClass('AVCaptureDevice');
					AVCaptureDevice.requestAccessForMediaTypeCompletionHandler('vide', (granted) => {
						if (granted) {
							resolve();
						} else {
							reject('权限被拒绝');
						}
					});
				});
			},

			// 显示权限引导弹窗
			async showAuthModal(title, content) {
				return new Promise((resolve) => {
					uni.showModal({
						title: title || '需要权限',
						content: content || '请允许权限以继续操作',
						confirmText: '去设置',
						success: (res) => {
							if (res.confirm) {
								// #ifdef MP-WEIXIN
								uni.openSetting();
								// #endif
								// #ifdef APP-PLUS
								plus.runtime.openSettings();
								// #endif
							}
							resolve();
						}
					});
				});
			},

			// 扫码错误处理
			handleScanError(err) {
				let errMsg = '扫码失败';

				if (err.errMsg) {
					if (err.errMsg.includes('cancel')) {
						errMsg = '已取消扫码';
					} else if (err.errMsg.includes('camera')) {
						errMsg = '相机不可用';
					}
				} else if (err.message) {
					errMsg = err.message;
				}

				// 如果是权限问题，引导用户去设置
				if (errMsg.includes('拒绝') || errMsg.includes('denied') || errMsg.includes('permission')) {
					this.showAuthModal('相机权限已关闭', '请到系统设置中允许访问相机');
					return;
				}

				uni.showToast({
					title: errMsg,
					icon: 'none',
					duration: 2000
				});
			},
		}
	}
</script>

<style>

</style>